<template>
    <div id="canvasBody">

        <!-- 画布 -->
        <div ref="imgContainer" class="imgContainer">
            <canvas ref="canvas" id="labelCanvas" width="500" height="500"></canvas>
            <canvas ref="canvas1" id="labelCanvas1" width="500" height="500" style="display: none;"></canvas>
        </div>

        <!-- 按钮布局 -->
        <div class="iconFlex">
            <div class="btnOnBox">
                <el-tooltip content="矩形" placement="bottom" effect="light">
                    <el-button circle @click="selectChange('rect')">
                        <i><svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-juxing"></use>
                            </svg></i>
                    </el-button>
                </el-tooltip>
                <el-tooltip content="圆形" placement="bottom" effect="light">
                    <el-button circle @click="selectChange('circle')"><i>
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-caozuojiemiantubiao---_yuanxinhuayuanhu"></use>
                            </svg></i></el-button>
                </el-tooltip>
                <!-- <el-tooltip content="圆形" placement="bottom" effect="light">
                    <el-button circle @click="selectChange('default')"><i>
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-caozuojiemiantubiao---_yuanxinhuayuanhu"></use>
                            </svg></i></el-button>
                </el-tooltip> -->
                <el-tooltip content="清空画布" placement="bottom" effect="light">
                    <el-button circle @click="resetCanvas()"><i>
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-qingkongshuju"></use>
                            </svg></i></el-button>
                </el-tooltip>
            </div>
            <div class="colorCenter">
                <span class="labeStyle">
                    字体颜色:
                    <el-color-picker style="margin-right: 5px" v-model="fontColorInit.fontColor" show-alpha />
                </span>
                <span class="labeStyle">
                    背景颜色:
                    <el-color-picker v-model="fontColorInit.backColor" show-alpha />
                </span>
            </div>
            <div class="imgDown">
                <el-upload ref="uploadFile" :file-list="fileList" :action="qiNiuUrl" :headers="{
                    Authorization: 'Bearer ' + getToken(),
                }" :limit="1" :on-success="onSuccess" :on-error="onError" :on-exceed="onExceed">
                    <el-tooltip content="添加图片" placement="bottom" effect="light">
                        <el-button circle><i>
                                <svg class="icon" aria-hidden="true">
                                    <use xlink:href="#icon-tianjiatupian"></use>
                                </svg></i></el-button>
                    </el-tooltip>
                </el-upload>
            </div>
            <el-divider />
            <div style="height: 65%; overflow-y: auto">
                <div style="margin-top: 20px" v-for="(item, index) in props.modelValue.allAngList" :key="index"
                    class="addListClass">
                    <div class="labeStyle"></div>
                    <div>
                        <div class="labeStyle">
                            {{ index + 1 }}、百分比:
                            <el-input v-model="item.optionPercentValue" :autosize="{ minRows: 1 }" style="width: 48px" />
                            %
                        </div>
                        <div style="display: flex">
                            <div class="labeStyle" style="line-height: 32px">内容：</div>
                            <el-input v-model="item.optionTextValue" :autosize="{ minRows: 1, maxRows: 4 }"
                                placeholder="请输入内容" type="textarea" style="width: 394px" />
                            <!-- <el-button @click="equivalent(index)" type="primary">添加等效答案</el-button> -->
                            <el-button @click="modify(item)" type="primary">修改</el-button>
                            <el-button @click="detList(item)" type="primary">删除</el-button>
                        </div>
                        <!-- <div v-if="item.equalAnswers">
                            <div v-for="(itemDouble, indexDouble) in item.equalAnswers" :key="itemDouble.id"
                                class="labeStyle" style="display: flex">
                                <div class="labeStyle" style="line-height: 32px">
                                    等效答案{{ indexDouble + 1 }}：
                                </div>
                                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" style="width: 394px"
                                    v-model="itemDouble.equalAnswerEditorValue" placeholder="请输入等效答案" />
                            </div>
                        </div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <el-dialog v-model="dialogFormVisible.status" :title="currentType == 'rect' ? '添加矩形区域' : '添加圆形区域'">
        <el-form :model="form">
            <el-form-item size="default" label="区域内容:" label-width="140px">
                <el-input v-model="dialogFormVisible.form.optionTextValue" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogChangeFn()">取消</el-button>
                <el-button type="primary" @click="resetForm()">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { getCurrentInstance, toRefs, ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import "../../iconFont/canvasIcon/iconfont";
import { uuid } from "vue3-uuid";
import { getToken } from "../../utils/auth.js";
import 'fabric/dist/fabric.js';
onMounted(() => {
    initEditorCanvas();
    initD();
});

const props = defineProps({
    modelValue: {
        type: [String, Object, Array],
        default: null,
    },
});


// 外部盒子ref
const imgContainer = ref(null)

// 字体选择色号
const fontColorInit = reactive({
    fontColor: "rgba(255, 255, 255, 1)",
    backColor: "rgba(59, 203, 133, 0.57)"
});

// 实际照片大小
const ImageSize = reactive({
    width: null,
    height: null
});

// 实际外部盒子大小
const BoxSize = reactive({
    width: 500,
    height: 500
})

// 初始坐标
const mouseFrom = reactive({
    x: null, y: null
});

//  移动时坐标
const mouseTo = reactive({
    x: null,
    y: null
})
// 绘画类型 
const currentType = ref('default');

// 圆形图形初始化
const currentCircle = ref(null);
// 照片挂载成功
const drawImage = ref(null);

// 添加文字弹框
const dialogFormVisible = reactive({
    status: false,
    form: {
        optionTextValue: null
    }
})
const fileList = ref([])
// 开始绘画
const isDrawing = ref(false)
// 图片上传
const uploadFile = ref(null);
// proxy
const { proxy } = getCurrentInstance();
// 上传action
const qiNiuUrl = ref(proxy.apiPath + "/api/oss/aliyun/upload");
// canvas 挂载实例
// const editorCanvas = ref(null);
let editorCanvas = null;
// 当前图形对象
const drawingObject = ref(null)

const activeEl = ref(null);

let allAngList = ref([]);

// 数据转换的定位
let positionRectCr = reactive({
    top: null,
    left: null,
    width: null,
    height: null,
    radius: null
})
/**
 *    以
 *    下
 *    是
 *    函                                                               
 *    数
 *    事
 *    件
 *    部
 *    分
 *  */

// 上传成功
const onSuccess = (res) => {
    if (res.code == 200) {
        props.modelValue.imgUrl = proxy.apiPath + res.path;
        // console\.log(imgPath);
        getImageSize(res.path).then(res => {
            const Image = res;
            ImageSize.width = Image.width;
            ImageSize.height = Image.height;
            const imgWH = changeOldPointToNewPoint(ImageSize.width, ImageSize.height, BoxSize.width, BoxSize.height);
            const scaleX = imgWH[0] / ImageSize.width;
            const scaleY = imgWH[1] / ImageSize.height;
            props.modelValue.ConstKx = ImageSize.width / imgWH[0];
            props.modelValue.ConstKy = ImageSize.height / imgWH[1];
            drawImage.value = true;
            editorCanvas.setBackgroundImage(
                props.modelValue.imgUrl,
                editorCanvas.renderAll.bind(editorCanvas), // 刷新画布
                {
                    scaleX,
                    scaleY,
                    originX: "left",
                    originY: "top",
                    left: 0,
                    top: 0,
                }
            );
        });
    }
};
// 上传失败
const onError = () => {
    //上传失败
    proxy.Message.error("上传失败!");
};
const onExceed = (files) => {
    //覆盖上一个文件
    uploadFile.value.clearFiles();
    const file = files[0];
    uploadFile.value.handleStart(file);
    uploadFile.value.submit();
};
// 根据网络地址获取图片的宽高
function getImageSize(img) {
    let image = new Image()
    image.crossOrigin = '';
    image.src = (props.modelValue.imgUrl ? props.modelValue.imgUrl : proxy.apiPath + img) + `?timeStamp=${new Date()}`;
    return new Promise((resolve, reject) => {
        image.onload = function () {
            const { width, height } = image
            resolve({ width, height })
        }
    })
};
let editorCanvas1 = null;
// 初始化画布
function initEditorCanvas() {
    // 初始化canvas
    editorCanvas = new fabric.Canvas("labelCanvas", {
        width: BoxSize.width, // canvas 宽
        height: BoxSize.height,
        backgroundColor: "#ffffff",
        transparentCorners: true,
        fireRightClick: true, // 启用右键，button的数字为3
        stopContextMenu: true, // 禁止默认右键菜单
    });

    editorCanvas1 = new fabric.Canvas("labelCanvas1", {
        width: BoxSize.width, // canvas 宽
        height: BoxSize.height,
        backgroundColor: "#ffffff",
        transparentCorners: true,
        fireRightClick: true, // 启用右键，button的数字为3
        stopContextMenu: true, // 禁止默认右键菜单
    });

    if (props.modelValue.str && props.modelValue.imgUrl) {
        const str = JSON.parse(props.modelValue.str)
        getImageSize(props.modelValue.imgUrl).then(res => {
            const Image = res;
            ImageSize.width = Image.width;
            ImageSize.height = Image.height;
            const imgWH = changeOldPointToNewPoint(ImageSize.width, ImageSize.height, BoxSize.width, BoxSize.height);
            const scaleX = imgWH[0] / ImageSize.width;
            const scaleY = imgWH[1] / ImageSize.height;
            props.modelValue.ConstKx = ImageSize.width / imgWH[0];
            props.modelValue.ConstKy = ImageSize.height / imgWH[1];
            drawImage.value = true;
            editorCanvas.setBackgroundImage(
                props.modelValue.imgUrl,
                editorCanvas.renderAll.bind(editorCanvas), // 刷新画布
                {
                    scaleX,
                    scaleY,
                    originX: "left",
                    originY: "top",
                    left: 0,
                    top: 0,
                }
            );
        });
        editorCanvas.loadFromJSON(
            str,
            editorCanvas.renderAll.bind(editorCanvas),
            function (o, object) {
                // `o` = json object
                // `object` = fabric.Object instance
                // ... do some stuff ...
                // console.log('objqwe', o, object)
            }
        );

    }

};
// 添加画布事件
function initD() {
    editorCanvas.on("mouse:down", canvasMouseDown);
    // 监听鼠标移动
    editorCanvas.on("mouse:move", canvasMouseMove);
    editorCanvas.on("mouse:up", canvasMouseUp);
    editorCanvas.on("object:moving", (e) => {
        // console\.log(e);
        // 边界处理
        var obj = e.target;
        // if object is too big ignore
        if (
            obj.currentHeight > obj.canvas.height ||
            obj.currentWidth > obj.canvas.width
        ) {
            return;
        }
        obj.setCoords();
        // top-left  corner
        if (obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
            obj.top = Math.max(obj.top, obj.top - obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left - obj.getBoundingRect().left);
        }
        // bot-right corner
        if (
            obj.getBoundingRect().top + obj.getBoundingRect().height >
            obj.canvas.height ||
            obj.getBoundingRect().left + obj.getBoundingRect().width >
            obj.canvas.width
        ) {
            obj.top = Math.min(
                obj.top,
                obj.canvas.height -
                obj.getBoundingRect().height +
                obj.top -
                obj.getBoundingRect().top
            );
            obj.left = Math.min(
                obj.left,
                obj.canvas.width -
                obj.getBoundingRect().width +
                obj.left -
                obj.getBoundingRect().left
            );
        }
    });

    editorCanvas.on("object:scaling", (options) => {
        // console.log("scale", options);
        var text = options.target.item(1);
        let group = options.target;
        // console\.log("text", text.width, group.width, group.getScaledWidth());
        let scaleX = group.width / group.getScaledWidth();
        let scaleY = group.height / group.getScaledHeight();
        text.set({
            fontSize: 14,
            scaleX,
            scaleY,
        });
    });

    editorCanvas.on('mouse:wheel', opt => {
        let delta = opt.e.deltaY // 滚轮，向上滚一下是 -100，向下滚一下是 100
        let zoom = editorCanvas.getZoom() // 获取画布当前缩放值
        zoom *= 0.999 ** delta
        if (zoom > 20) zoom = 20
        if (zoom < 0.01) zoom = 0.01
        editorCanvas.zoomToPoint({ // 关键
            x: opt.e.offsetX,
            y: opt.e.offsetY
        },
            zoom
        )
        opt.e.preventDefault()
        opt.e.stopPropagation()
    })
};
async function toUrl() {

    let strSv = JSON.parse(props.modelValue.str);
    strSv.objects.forEach((item, index) => {
        item.objects[1].text = String(index + 1)
    });
    await editorCanvas1.loadFromJSON(
        JSON.stringify(strSv),
        editorCanvas1.renderAll.bind(editorCanvas1),
        function (o, object) {
            let str = String(editorCanvas1.toSVG());
            props.modelValue.svgStr = str.substring(str.indexOf('<svg'), str.indexOf('</svg>') + 6);
            // `o` = json object
            // `object` = fabric.Object instance
            // ... do some stuff ...
            // console.log('objqwe', o, object)
            //         console.log(editorCanvas1.getObjects());
            //         let str = String(editorCanvas1.toSVG());
            // props.modelValue.svgStr = str.substring(str.indexOf('<svg'), str.indexOf('</svg>') + 6);
            // console.log(props.modelValue.svgStr);
            // let reg = /^\<svg.*?\<\/svg\>/gi;
        }
    );
    // console.log(editorCanvas1.getObjects());
    // let str = String(editorCanvas1.toSVG());
    // props.modelValue.svgStr = str.substring(str.indexOf('<svg'), str.indexOf('</svg>') + 6);
    // console.log(props.modelValue.svgStr);
    // let reg = /^\<svg.*?\<\/svg\>/gi;
};
// 鼠标点击
function canvasMouseDown(options) {

    if (!drawImage.value) return;
    // // console\.log(!editorCanvas.getActiveObject());
    // // console\.log(options);
    // 记录当前鼠标的起点坐标
    if (!editorCanvas.getActiveObject()) {
        isDrawing.value = true;  // 开始绘画
        mouseFrom.x = options.absolutePointer.x;
        mouseFrom.y = options.absolutePointer.y;
        if (currentType.value == 'circle') {
            currentCircle.value = new fabric.Circle({
                top: mouseFrom.y,
                left: mouseFrom.x,
                radius: 0,
                fill: 'rgba(299, 23, 155, 0.3)',
                stroke: 'rgba(0, 0, 0, 0.2)'
            })
            editorCanvas.add(currentCircle.value)
        }
        // else {
        //     mouseFrom.x = options.absolutePointer.x;
        //     mouseFrom.y = options.absolutePointer.y;
        // }
    };
};

// 鼠标移动
function canvasMouseMove(options) {
    if (!drawImage.value) return;
    // // console\.log("move", options);
    if (!editorCanvas.getActiveObject()) {  // 判断当前有没有选中元素
        // console.log("move");
        if (currentType.value == 'circle' && currentCircle.value) {
            const currentPoint = options.absolutePointer;
            let radius = Math.min(Math.abs(mouseFrom.x - currentPoint.x), Math.abs(mouseFrom.y - currentPoint.y)) / 2;
            let top = currentPoint.y > mouseFrom.y ? mouseFrom.y : mouseFrom.y - radius * 2;
            let left = currentPoint.x > mouseFrom.x ? mouseFrom.x : mouseFrom.x - radius * 2;
            currentCircle.value.set('radius', radius);
            currentCircle.value.set('top', top);
            currentCircle.value.set('left', left);
            editorCanvas.requestRenderAll();

        } else if (currentType.value == 'rect') {
            mouseTo.x =
                options.pointer.x > editorCanvas.width
                    ? editorCanvas.width
                    : options.pointer.x;
            mouseTo.y =
                options.pointer.y > editorCanvas.height
                    ? editorCanvas.height
                    : options.pointer.y;
        };
    }
};
// 鼠标抬起
function canvasMouseUp(options) {
    if (!drawImage.value) return;

    isDrawing.value = false;
    if (
        !editorCanvas.getActiveObject() &&
        currentType.value == "rect"
    ) {
        // 解决绘制的时候超出边界
        mouseTo.x =
            options.pointer.x > editorCanvas.width
                ? editorCanvas.width
                : options.pointer.x;
        mouseTo.y =
            options.pointer.y > editorCanvas.height
                ? editorCanvas.height
                : options.pointer.y;

        // 宽高为负值或为0
        let width = mouseTo.x - mouseFrom.x;
        let height = mouseTo.y - mouseFrom.y;
        // 如果点击和松开鼠标，都是在同一个坐标点或者反向，不绘制矩形
        if (width <= 0 || height <= 0) return;
        // drawImage.value && (drawRect());
        drawRect()

    } else if (currentType.value == "circle") {
        // console\.log(JSON.stringify(mouseFrom), JSON.stringify(options.absolutePointer));
        // if (JSON.stringify(mouseFrom) === JSON.stringify(options.absolutePointer)) {
        //     editorCanvas.remove(currentCircle.value);

        // } else {
        //     if (currentCircle.value) {
        //         currentCircle.value.set('stroke', '#000')
        //     }
        // }
        editorCanvas.remove(currentCircle.value);
        currentCircle.value = null;

        // drawImage.value && (drawRect(options));
        drawRect(options)
    }
    // currentType.value = 'default'
    editorCanvas.renderAll();
    // console.log(editorCanvas.getObjects());
    // console.log(editorCanvas.getActiveObject());
    if (editorCanvas.getActiveObject()) {
        const getActiveObject = editorCanvas.getActiveObject();
        // console.log(getActiveObject);
        props.modelValue.allAngList.forEach((item) => {
            // console.log(item.optionUuid, getActiveObject.rectId);
            if (item.optionUuid == getActiveObject.rectId) {
                if (item.driveSwitch == 2) {
                    item.originX1 = (getActiveObject.left - 0) * props.modelValue.ConstKx;
                    item.originY1 = (getActiveObject.top - 0) * props.modelValue.ConstKy;
                    item.originX2 = (getActiveObject.left - 0 + (getActiveObject.width - 0) * getActiveObject.scaleX) * props.modelValue.ConstKx;
                    item.originY2 = (getActiveObject.top - 0 + (getActiveObject.height - 0) * getActiveObject.scaleY) * props.modelValue.ConstKy;
                } else if (item.driveSwitch == 1) {
                    item.originX1 = (getActiveObject.left - 0 + (getActiveObject.width / 2) * getActiveObject.scaleX) * props.modelValue.ConstKx;
                    item.originY1 = (getActiveObject.top - 0 + (getActiveObject.height / 2) * getActiveObject.scaleY) * props.modelValue.ConstKy;
                    item.originX2 = (getActiveObject.left - 0 + (getActiveObject.width / 2) * getActiveObject.scaleX) * props.modelValue.ConstKx;
                    item.originY2 = (getActiveObject.top - 0 + getActiveObject.height * getActiveObject.scaleY) * props.modelValue.ConstKy;
                }
            }
        })
        // console.log(props.modelValue.allAngList);
    }
    props.modelValue.str = JSON.stringify(
        editorCanvas.toJSON(['rectId'])
    );
    toUrl()
    // console.log(props.modelValue);
}
let rectId = ref(null)
// 添加文字
function drawRect(options) {
    // console\.log("绘图啦11111", mouseFrom, mouseTo);
    // 通过UUID拿到唯一的ID
    rectId.value = uuid.v1();
    /**
     * 删除之前的this.drawingObject
     */
    // console\.log(drawingObject.value);
    if (drawingObject.value) {
        editorCanvas.remove(drawingObject.value);
    }
    drawingObject.value = null;
    if (currentType.value == "rect") {
        // 计算矩形长宽
        positionRectCr.left = mouseFrom.x;
        positionRectCr.top = mouseFrom.y;
        positionRectCr.width = mouseTo.x - mouseFrom.x;
        positionRectCr.height = mouseTo.y - mouseFrom.y;
        const drawingObject = new fabric.Rect({
            width: positionRectCr.width,
            height: positionRectCr.height,
            fill: fontColorInit.backColor,
            lockRotation: true,
            // opacity: 0.5,
            rectId: rectId.value,
            lockScalingFlip: true, // 禁止负值反转
            originX: "center",
            originY: "center",
        });
        const text = new fabric.Textbox("", {
            // width,
            // height,
            fontFamily: "Helvetica",
            fill: fontColorInit.fontColor, // 设置字体颜色
            fontSize: 16,
            textAlign: "center",
            rectId: rectId.value,
            lockScalingX: true,
            lockScalingY: true,
            lockScalingFlip: true, // 禁止负值反转
            originX: "center",
            originY: "center",
        });
        // console\.log(drawingObject);
        if (drawingObject) {
            const group = new fabric.Group([drawingObject, text], {
                rectId: rectId.value,
                left: positionRectCr.left,
                top: positionRectCr.top,
                width: positionRectCr.width,
                height: positionRectCr.height,
                lockScalingFlip: true,
                lockRotation: true,
            });
            editorCanvas.add(group);
            // console\.log("editorCanvas", editorCanvas);
            editorCanvas.renderAll();
            drawingObject.value = drawingObject;

            // 绘制完成展示右键菜单栏（因为在鼠标绘制时，通过mouseup拿不到绘制的内容）
            let len = editorCanvas._objects.length;
            let curOptions = editorCanvas._objects[len - 1];
            // this.showMenuCon(curOptions);
            activeEl.value = curOptions;
            dialogFormVisible.status = true
        }
    } else if (currentType.value == "circle") {
        const currentPoint = options.absolutePointer;
        positionRectCr.radius = Math.min(Math.abs(mouseFrom.x - currentPoint.x), Math.abs(mouseFrom.y - currentPoint.y)) / 2;
        positionRectCr.top = currentPoint.y > mouseFrom.y ? mouseFrom.y : mouseFrom.y - positionRectCr.radius * 2;
        positionRectCr.left = currentPoint.x > mouseFrom.x ? mouseFrom.x : mouseFrom.x - positionRectCr.radius * 2;
        const drawingObject = new fabric.Circle({
            radius: positionRectCr.radius,
            fill: fontColorInit.backColor,
            lockRotation: true,
            // opacity: 0.5,
            rectId: rectId.value,
            lockScalingFlip: true, // 禁止负值反转
            originX: "center",
            originY: "center",
        });
        const text = new fabric.Textbox("", {
            width: positionRectCr.radius,
            height: positionRectCr.radius,
            fontFamily: "Helvetica",
            fill: fontColorInit.fontColor, // 设置字体颜色
            fontSize: 16,
            textAlign: "center",
            rectId: rectId.value,
            lockScalingX: true,
            lockScalingY: true,
            lockScalingFlip: true, // 禁止负值反转
            originX: "center",
            originY: "center",
        });
        if (drawingObject) {
            const group = new fabric.Group([drawingObject, text], {
                rectId: rectId.value,
                left: positionRectCr.left,
                top: positionRectCr.top,
                width: positionRectCr.radius * 2,
                height: positionRectCr.radius * 2,
                lockScalingFlip: true,
                lockRotation: true,
            });
            // console\.log(group);
            editorCanvas.add(group);
            // console\.log("editorCanvas", editorCanvas);
            editorCanvas.renderAll();
            drawingObject.value = drawingObject;
            // 绘制完成展示右键菜单栏（因为在鼠标绘制时，通过mouseup拿不到绘制的内容）
            let len = editorCanvas._objects.length;
            let curOptions = editorCanvas._objects[len - 1];
            // this.showMenuCon(curOptions);
            activeEl.value = curOptions;
            dialogFormVisible.status = true
        }
    }
};
// 弹框取消
function dialogChangeFn() {
    dialogFormVisible.status = false;
};

let arrObj = ref(null)
// 弹框确认
function resetForm() {
    // console\.log(editorCanvas.getObjects());
    if (activeEl.value) {
        let test = dialogFormVisible.form.optionTextValue;
        let textID = rectId.value;
        editorCanvas.getObjects().forEach((item) => {
            // console\.log("item", item);
            if (item.rectId == activeEl.value.rectId) {
                item.set({
                    textID: textID,
                });
                item.item(1).set({
                    text: test,
                    originX: "center",
                    originY: "center",
                    textAlign: "center",
                });
            }
        });

        if (currentType.value == 'rect') {
            arrObj.value = {
                optionTextValue: test,
                optionUuid: textID,
                optionPercentValue: 100,
                imgScale: 1,
                optionIndex: props.modelValue.allAngList.length == 0 ? 1 : (props.modelValue.allAngList[props.modelValue.allAngList.length - 1].optionIndex + 1),
                driveSwitch: currentType.value == 'rect' ? 2 : currentType.value == 'circle' ? 1 : null,
                "originX1": (positionRectCr.left - 0) * props.modelValue.ConstKx,
                "originY1": (positionRectCr.top - 0) * props.modelValue.ConstKy,
                "originX2": (positionRectCr.left - 0 + positionRectCr.width - 0) * props.modelValue.ConstKx,
                "originY2": (positionRectCr.top - 0 + positionRectCr.height - 0) * props.modelValue.ConstKy,
                "fontSize": 22,
                "backColor": "rgba(59, 203, 133, 0.57)",
                "fontColor": "rgba(255, 255, 255, 1)",
                "equalAnswers": [],
            }
        } else if (currentType.value == 'circle') {
            arrObj.value = {
                optionTextValue: test,
                optionUuid: textID,
                optionPercentValue: 100,
                imgScale: 1,
                optionIndex: props.modelValue.allAngList.length == 0 ? 1 : (props.modelValue.allAngList[props.modelValue.allAngList.length - 1].optionIndex + 1),
                driveSwitch: currentType.value == 'rect' ? 2 : currentType.value == 'circle' ? 1 : null,
                "originX1": (positionRectCr.left - 0 + positionRectCr.radius - 0) * props.modelValue.ConstKx,
                "originY1": (positionRectCr.top - 0 + positionRectCr.radius - 0) * props.modelValue.ConstKy,
                "originX2": (positionRectCr.left - 0 + (positionRectCr.radius - 0) * 2) * props.modelValue.ConstKx,
                "originY2": (positionRectCr.top - 0 + (positionRectCr.radius - 0) * 2) * props.modelValue.ConstKy,
                "fontSize": 22,
                "backColor": "rgba(59, 203, 133, 0.57)",
                "fontColor": "rgba(255, 255, 255, 1)",
                "equalAnswers": [],
            }
        }
        props.modelValue.allAngList.push(arrObj.value);
        // console.log(props.modelValue.allAngList);
    }
    editorCanvas.requestRenderAll()
    // currentType.value = 'default'

    selectChange('default');
    dialogFormVisible.status = false;
    dialogFormVisible.form.optionTextValue = null;
    // drawRect()
    props.modelValue.str = JSON.stringify(
        editorCanvas.toJSON(['rectId']));
    toUrl()
};
// 切换图形
function selectChange(graph) {
    currentType.value = graph; // 给画图状态赋值
    switch (graph) {
        case 'circle':
            editorCanvas.selectionColor = 'transparent';
            editorCanvas.selectionBorderColor = 'transparent';
            editorCanvas.skipTargetFind = true // 禁止选中
            break;
        case 'rect':
            editorCanvas.selectionColor = 'rgba(100, 100, 255, 0.3)'
            editorCanvas.selectionBorderColor = 'rgba(255, 255, 255, 0.3)'
            editorCanvas.skipTargetFind = true // 禁止选中    
            break;
        case 'default':
            editorCanvas.selection = true
            editorCanvas.selectionColor = 'rgba(100, 100, 22, 0.3)'
            editorCanvas.selectionBorderColor = 'rgba(255, 255, 255, 0.3)'
            editorCanvas.skipTargetFind = false // 禁止选中
        default: break;
    }
};
// 清空画布
function resetCanvas() {
    editorCanvas.clear();
    drawImage.value = false;
    props.modelValue.allAngList = []
};
// 在实际盒子上的照片大小
function changeOldPointToNewPoint(imgW, imgH, canvasW, canvasH) {
    let tmpW = canvasW;
    let tmpH = (tmpW * imgH) / imgW;
    if (tmpH <= canvasH) {
        return [tmpW, tmpH];
    } else {
        tmpW = canvasW;
        tmpH = (tmpW * imgH) / imgW;
        let count = 1;
        let raise = 0.05;
        while (tmpH > canvasH || tmpW > canvasW) {
            tmpW = tmpW * (1 - raise * count);
            tmpH = (tmpW * imgH) / imgW;
        }
        return [tmpW, tmpH];
    }
};
// 修改显示内容
function modify(options) {
    // console.log(options);
    // console.log(editorCanvas.getObjects());
    editorCanvas.getObjects().forEach((item) => {
        // // console\.log("item", item);
        if (item.rectId == options.optionUuid) {

            item.item(1).set({
                text: options.optionTextValue,
                originX: "center",
                originY: "center",
                textAlign: "center",
            });
        }
    });
    editorCanvas.requestRenderAll()
    props.modelValue.str = JSON.stringify(
        editorCanvas.toJSON(['rectId'])
    );
    toUrl()
}
// 删除操作
function detList(options) {
    editorCanvas.getObjects().forEach((item) => {
        // console\.log("item", item);
        if (item.textID == options.optionUuid) {
            editorCanvas.remove(item)
        }
    });
    props.modelValue.allAngList = props.modelValue.allAngList.filter((item) => item.optionUuid !== options.optionUuid)
    // // console\.log(allAngList.value);
    editorCanvas.requestRenderAll()
    props.modelValue.str = JSON.stringify(
        editorCanvas.toJSON(['rectId'])
    );
    toUrl()
}
</script>

<style lang="scss" scoped>
#canvasBody {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-evenly;
}

canvas {
    display: block;
    margin: 0 auto;
    border: 2px solid rgb(214, 207, 207);
    border-radius: 10px;
}

.icon {
    width: 1.2em;
    height: 1.2em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}

.labeStyle {
    font-size: 14px;
    color: #606266;
    font-weight: 600;
}

.el-input {
    width: 500px;
}

.imgContainer {
    width: 500px;
    height: 500px;
}

.iconFlex {
    height: 500px;
    width: 44%;

    & div {
        margin-bottom: 15px;

        span {
            margin-right: 10px;
        }
    }
}

.el-button.is-circle {
    border-radius: 50%;
    padding: 8px;
    margin-right: 9px;
}

.addListClass {
    display: flex;
}

.el-form-item--default {

    margin-top: 50px;
}

#labelCanvas {
    position: relative;
    box-shadow: 0 0 25px #cac6c6;
    width: 100%;
    display: block;
    // margin: 15px auto;
    height: 100%;

    #editDel {
        position: absolute;
        // top: 50%;
        // left: 50%;
        // transform: translate(-50%, -50%);
        width: 100px;
        height: 100px;
        line-height: 100px;
        background: red;
        color: white;
        text-align: center;
        margin: auto auto;
    }
}
</style>
